package com.taldh.algorithm.array;

import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;

public class SortedSquares {

    public int[] sortedSquares(int[] A) {
        int len = A.length;
        int[] ans = new int[len];

        int i = 0;
        int j = len - 1;
        while (i <= j) {
            if (A[i] < 0) {
                A[i] = A[i] * A[i];
                i++;
            } else {
                A[j] = A[j] * A[j];
                j--;
            }
        }

        if (A.length <= 1) {
            return A;
        }

        j += 1;
        i -= 1;
        int ansIndex = 0;
        while (ansIndex < len) {
            if (j >= len || (i >= 0 && A[i] < A[j])) {
                ans[ansIndex++] = A[i--];
            } else {
                ans[ansIndex++] = A[j++];
            }
        }

        return ans;
    }

    @Test
    public void test() {
        Assert.assertArrayEquals(new int[]{0,1,9,16,100}, sortedSquares(new int[]{-4,-1,0,3,10}));
    }

    @Test
    public void test1() {
        Assert.assertArrayEquals(new int[]{4,9,9,49,121}, sortedSquares(new int[]{-7,-3,2,3,11}));
    }

    @Test
    public void test2() {
        Assert.assertArrayEquals(new int[]{1,4,4}, sortedSquares(new int[]{-1,2,2}));
    }

}